<?php
/**
 * @package Admin
 */

if ( !defined( 'BIGCKOOL_VERSION' ) ) {
	header( 'HTTP/1.0 403 Forbidden' );
	die;
}

/**
 * Class that holds most of the admin functionality for WP SEO.
 */
class BIGCKOOL_Admin {
	private $FB;
	private $optionfb;
	/**
	 * Class constructor
	 */
	function __construct() {
		
		//add likecount column
		add_filter('manage_posts_columns', array($this,'votecount_columns') );
		add_action('manage_posts_custom_column',  array($this,'votecount_show_columns'), 10, 2);
		add_filter( 'manage_edit-post_sortable_columns', array($this,'votecount_sortable_column') );
		add_action( 'pre_get_posts', array($this,'my_votecount_orderby'));
		
		//add bulk action
		add_action('admin_footer-edit.php', array(&$this, 'custom_bulk_admin_footer'));
		add_action('load-edit.php',         array(&$this, 'custom_bulk_action'));
		add_action('admin_notices',         array(&$this, 'custom_bulk_admin_notices'));
	
		//default value for post
		add_filter( 'wp_insert_post_data', array($this,'default_votecount'), '99', 2 );

		add_action( 'admin_menu', array( $this, 'register_settings_page' ), 5 );
		add_action( 'admin_init', array( $this, 'options_init' ) );
		
		
		//facebook
		$this->optionfb=get_option('bigckool_option_fb');
		require_once(BIGCKOOL_PATH . 'facebook-php-sdk/facebook.php');			
			$config = array(
		      'appId' => $this->optionfb['app_id'],
		      'secret' => $this->optionfb['app_secret'],
				'cookie' => false
		  );

	  	$this->FB = new Facebook($config); 
	}
	

	/**
	 * Register the menu item and its sub menu's.
	 *
	 * @global array $submenu used to change the label on the first item.
	 */
	function register_settings_page() {
		$hook =add_menu_page( 'BigC Kool','BigC Kool', 'edit_posts', 'bigckool_setting',array( $this, 'setting' ),BIGCKOOL_URL . 'images/logo.png');
		//add_action( "load-$hook", 'add_dashboard_options' );
		//add_action( 'admin_head', 'dashboard_header'  );	    
	    
		
		//add_submenu_page( 'bigckool_dashboard', 'BigC Kool Dashboard','Dashboard','manage_options','bigckool_dashboard',array( $this, 'dashboard' ));
		//add_submenu_page( 'bigckool_dashboard', 'BigC Kool Setting','Setting','manage_options','bigckool_setting',array( $this, 'setting' ));
		
		//hidden page
		$hook =add_submenu_page( null, null,'Detail','edit_posts','bigckool_post_detail',array( $this, 'post_detail' ));
		add_action( "load-$hook", 'add_dashboard_options' );
		add_action( 'admin_head', 'dashboard_header'  );
	}
	
/**
	 * Register all the options needed for the configuration pages.
	 */
	function options_init() {
		
		register_setting(
            'bigckool_option_group', // Option group
            'bigckool_option_fb'
        );

        
	}
	/**
	 * Loads the form for the network configuration page.
	 */
	function dashboard() {
		require( BIGCKOOL_PATH . '/admin/pages/dashboard.php' );
	}
function post_detail() {
		require( BIGCKOOL_PATH . '/admin/pages/detail.php' );
	}
	function setting() {
		if ( !current_user_can( 'edit_posts' ) )  {
			wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
		}
		require( BIGCKOOL_PATH . '/admin/pages/setting.php' );
	}

	function votecount_columns($columns) {
	    $columns['votecount'] = 'Likes';
	    return $columns;
	}
	
	function votecount_show_columns($name,$post) {
	    global $post;
	    switch ($name) {
	        case 'votecount':
	            $views = '<a href="'.admin_url('admin.php?page=bigckool_post_detail&postid='.$post->ID).'">'.get_post_meta($post->ID, 'votecount', true).'</a>';	            	            
            	echo $views;
	    }
	}
	
	function votecount_sortable_column( $columns ) {

	    $columns['votecount'] = 'votecount';
	 
	    //To make a column 'un-sortable' remove it from the array
	    //unset($columns['date']);
	 
	    return $columns;
	}
	
	function my_votecount_orderby( $query ) {
		if( ! is_admin() )
	        return;
	 
	    $orderby = $query->get( 'orderby');
	 
	    if( 'votecount' == $orderby ) {
	        $query->set('meta_key','votecount');
	        $query->set('orderby','meta_value_num');
	    }
	}
	
	function default_votecount( $data , $postarr ) {
		//t($postarr);
		if($postarr['ID']>0){
			add_post_meta($postarr['ID'],'votecount',0);			
		}
		return $data;
	}
	
	
/**
		 * Step 1: add the custom Bulk Action to the select menus
		 */
		function custom_bulk_admin_footer() {
			global $post_type;
			
			if($post_type == 'post') {
				?>
					<script type="text/javascript">
						jQuery(document).ready(function() {
							jQuery('<option>').val('fbsync').text('<?php _e('FB Sync')?>').appendTo("select[name='action']");
							jQuery('<option>').val('fbsync').text('<?php _e('FB Sync')?>').appendTo("select[name='action2']");
							jQuery('<option>').val('export').text('<?php _e('Export')?>').appendTo("select[name='action']");
							jQuery('<option>').val('export').text('<?php _e('Export')?>').appendTo("select[name='action2']");
						});
					</script>
				<?php
	    	}
		}
		
		
		/**
		 * Step 2: handle the custom Bulk Action
		 * 
		 * Based on the post http://wordpress.stackexchange.com/questions/29822/custom-bulk-action
		 */
		function custom_bulk_action() {
			global $typenow;
			$post_type = $typenow;
			
			if($post_type == 'post') {
				
				// get the action
				$wp_list_table = _get_list_table('WP_Posts_List_Table');  // depending on your resource type this could be WP_Users_List_Table, WP_Comments_List_Table, etc
				$action = $wp_list_table->current_action();
				
				$allowed_actions = array("fbsync","export");
				if(!in_array($action, $allowed_actions)) return;
				
				// security check
				//check_admin_referer('bulk-posts');
				
				// make sure ids are submitted.  depending on the resource type, this may be 'media' or 'ids'
				if(isset($_REQUEST['post'])) {
					$post_ids = array_map('intval', $_REQUEST['post']);
				}
				
				if(empty($post_ids)) return;
				
				// this is based on wp-admin/edit.php
				$sendback = remove_query_arg( array('exported', 'untrashed', 'deleted', 'ids'), wp_get_referer() );
				if ( ! $sendback )
					$sendback = admin_url( "edit.php?post_type=$post_type" );
				
				$pagenum = $wp_list_table->get_pagenum();
				$sendback = add_query_arg( 'paged', $pagenum, $sendback );
				
				switch($action) {
					
					case 'fbsync':
						
						// if we set up user permissions/capabilities, the code might look like:
						//if ( !current_user_can($post_type_object->cap->export_post, $post_id) )
						//	wp_die( __('You are not allowed to export this post.') );
						
						$exported = $this->perform_fbsync($post_ids);
						$sendback = add_query_arg( array('fbsync' => $exported, 'ids' => join(',', $post_ids) ), $sendback );
					break;
					case 'export':
						$exported = $this->perform_export($post_ids);
						$sendback = add_query_arg( array('export' => $exported, 'ids' => join(',', $post_ids) ), $sendback );
					break;
					
					default: return;
				}
				
				$sendback = remove_query_arg( array('action', 'action2', 'tags_input', 'post_author', 'comment_status', 'ping_status', '_status',  'post', 'bulk_edit', 'post_view'), $sendback );
				
				wp_redirect($sendback);
				exit();
			}
		}
		
		
		/**
		 * Step 3: display an admin notice on the Posts page after exporting
		 */
		function custom_bulk_admin_notices() {
			global $post_type, $pagenow;
			
			if($pagenow == 'edit.php' && $post_type == 'post' ) {
				if(isset($_REQUEST['fbsync']) && (int) $_REQUEST['fbsync']){
					$message = sprintf( _n( 'Posts sync.', '%s posts exported.', $_REQUEST['fbsync'] ), number_format_i18n( $_REQUEST['fbsync'] ) );
					echo "<div class=\"updated\"><p>{$message}</p></div>";
				}
				if(isset($_REQUEST['export']) && (int) $_REQUEST['export']){
					$message = sprintf( _n( 'Posts export.', '%s post(s) exported.', $_REQUEST['export'] ), number_format_i18n( $_REQUEST['export'] ) );
					echo "<div class=\"updated\"><p>{$message}</p></div>";
				}
			}
		}
		
		function perform_fbsync($post_ids) {
			//get array user like post
			$posturls=array();
			
			foreach($post_ids as $k=>$v){
				$posturls[$v]=$this->optionfb['app_url'].'/'.basename(get_permalink($v)).'/';				
			}			
		    $params = array(		
		        'method' => 'fql.query',		        	
		    	'access_token' => $this->FB->getAccessToken()	
		    );
		    
			//test get user like an url
			//$this->syncFBUserID();
			//$fbUserIDs=$this->getAllFBUserID();				
			if(count($posturls)>0){
				foreach($posturls as $k=>$v){
					//$params['query']='SELECT user_id FROM url_like WHERE user_id in ('.implode(',',$fbUserIDs).') and url ="'.$v.'"';
					$params['query']='select like_count from link_stat where url ="'.$v.'"';
					
					$userlikes=get_post_meta($k,'vote',1);
					
					if(!empty($userlikes))
					{
						//remove empty user
						unset($userlikes[""]);					
						//update list
						update_post_meta($k,'vote',$userlikes);
						//update count
						update_post_meta($k,'votecount',count($userlikes));		
					}
					//update count detail:
					/*
					if(count($userlikes)>0){						
						$metavalues=array();
						foreach($userlikes as $k2=>$v2){
							$metavalues[]=$v2['user_id'];
						}
						
						$args = array(
						    'meta_query' => array(						        
						        $metavalues
						    )
						);
						
						$args = array(
						    'meta_query' => array(
						        array(
						            'key' => 'fbid',
						            'value' =>$metavalues,
						            'compare' => 'IN'
						        ),
						    )
						);						
						$users= get_users($args);
						foreach($users as $k2=>$v2){
							$votes[]=$v2->data->ID;
						}
					}
					update_post_meta($k,'vote',$votes);
					*/
					
					
				}
			}			
			
			//query multi
			/*
			$params['method']='fql.multiquery';
		    $params['queries']=array('aaa'=>'SELECT user_id,url FROM url_like WHERE user_id in ("1772092360","100004363662880") and url ="http://colisshop.com/8-loai-qua-lam-dep-da-cho-ba-bau/"',
		    	'b'=>"select id from object_url where url in (".$posturls.")"
		    );
		    
		    
		    $result = $this->FB->api($params);
		     t($result);
			if(count($result>0)){
				foreach($result as $k=>$v){
					$params['query']='select id,url,site from object_url where id=\''.$v['id'].'\'';
					$userlikes = $this->FB->api($params);
					t($userlikes ,0);	
				}
			}
		    t($result);
			*/
			
			
			return true;
		}
		
		function perform_export($post_ids) {
			$exportdatas=array(array('Date','Video','fbid','User Name','Location','Gender'));
			//get user
			$args = array(
				'orderby' => 'id',
				'order' => 'DESC'
			);								
			$users= get_users($args);
			$posts=array();
			
			foreach($post_ids as $k=>$postid){
				//get post data
				$post=get_post($postid);
				$code=get_post_meta($postid,'code',1);
				$post->users=array();
				//get user like post:
				foreach($users as $k2=>$user){		
					$userdata=array();
					$userdata['ID']=$user->ID;
					$vote=get_post_meta($postid,'vote',1);
					
					if(!empty($vote) && array_key_exists($user->ID, $vote)){				
						$bd=get_user_meta($user->ID,'birthday',1);
						$userdata['display_name']=get_user_meta($user->ID,'fbname',1);
						$userdata['fbid']=get_user_meta($user->ID,'fbid',1);
						$userdata['user_email']=$user->data->user_email;
						$userdata['gender']=get_user_meta($user->ID,'gender',1);	
						$userdata['link']=get_user_meta($user->ID,'link',1);
						$userdata['birthday']=mktime(0,0,0,substr($bd,0,2),substr($bd,3,2),substr($bd,6,2));
						$userdata['location']=get_user_meta($user->ID,'location',1);
						$userdata['clickdate']=$vote[$user->ID]['time']+3600*(6.5);										
						$post->users[$user->ID]=$userdata;
						$exportdatas[]=array(date('d/m/Y h:i:s',$userdata['clickdate']),$code,$userdata['fbid'],$userdata['display_name'],$userdata['location'],$userdata['gender']);
					}
						
				}
				$posts[$postid]=$post;
				
			}			
			//export to excel
		   require BIGCKOOL_PATH.'php-excel.class.php';
		   $xls = new Excel_XML('UTF-8', false, 'Sheet1');
			$xls->addArray($exportdatas);
			$xls->generateXML('bigckool-'.date('d-m-Y-h-i',time()));
				
				return true;
		}
		
		function getAllFBUserID($isRemoveApp=true){
			$users= get_users();			
			$datausers=array();
			$postid=0;			
			foreach($users as $k=>$user){		
				$userdata=array();
				$userdata['ID']=$user->ID;
				$fbid=get_user_meta($user->ID,'fbid',1);
				if(!empty($fbid))$datausers[]=$fbid;
			}
			$params = array(		
		        'method' => 'fql.query',		        	
		    	'access_token' => $this->FB->getAccessToken()	
		    );
		    if($isRemoveApp){
				$params['query']='SELECT uid,user_likes FROM permissions WHERE uid in ('.implode(',',$datausers).')';
				unset($datausers);
				$result=$this->FB->api($params);
				foreach($result as $k=>$v)
					$datausers[]=$v['uid'];
		    }
			
			
			return $datausers;
		}
		
		function syncFBUserID(){
			$users= get_users();			
			$datausers=array();
			$postid=0;			
			foreach($users as $k=>$user){		
				$userdata=array();
				$userdata['ID']=$user->ID;
				$fblink=get_user_meta($user->ID,'link',1);				
				$urls=split('/',$fblink);
				if(count($urls)>0){				
					$fbid=str_replace('profile.php?id=', '', $urls[count($urls)-1]);
					//get userid
					if(!empty($fbid)){
						$result=$this->FB->api('/'.$fbid);						
						if(isset($result['id'])){							
							add_user_meta( $user->ID, 'fbid', $result['id'],1 );
						}
					}
					
				}				
					
			}
		}

}

//page function
function dashboard_header() {
    $page = ( isset($_GET['page'] ) ) ? esc_attr( $_GET['page'] ) : false;
    if( 'bigckool_dashboard' != $page )
    return;
    echo '<style type="text/css">';
    echo '.wp-list-table .column-id { width: 5%; }';
    echo '.wp-list-table .column-post_title { width: 40%; }';
    echo '.wp-list-table .column-post_name { width: 35%; }';
    echo '.wp-list-table .column-votecount { width: 20%;}';
    echo '</style>';
  }
function add_dashboard_options() {
	  $option = 'per_page';
	  $args = array(
	         'label' => 'Post per page',
	         'default' => 10,
	         'option' => 'post_per_page'
	         );
	  add_screen_option( $option, $args );
	}
	
function detail_header() {
    $page = ( isset($_GET['page'] ) ) ? esc_attr( $_GET['page'] ) : false;
    if( 'bigckool_dashboard' != $page )
    return;
    echo '<style type="text/css">';
    echo '.wp-list-table .column-id { width: 5%; }';
    echo '.wp-list-table .column-post_title { width: 40%; }';
    echo '.wp-list-table .column-post_name { width: 35%; }';
    echo '.wp-list-table .column-votecount { width: 20%;}';
    echo '</style>';
  }

	
add_filter('set-screen-option', 'test_table_set_option', 10, 3);
function test_table_set_option($status, $option, $value) {
  return $value;
}


// Globalize the var first as it's needed globally.
global $bigckool_admin;
$bigckool_admin = new BIGCKOOL_Admin();	
